package com.script

import com.entity.PackPath
import com.entity.PathUnionType
import com.utils.ScriptUtils.rootPath
import com.utils.ScriptUtils.script
import com.utils.YamlUtil
import java.util.*
import kotlin.system.exitProcess

// 默认的原始资源id
var oldIndex = 1
// 捕获控制台输出
val scanner = Scanner(System.`in`)

fun startScanner() {

    println("打包环境(其它退出)")
    println("1. 内网  2. staging  3. 正式")

    val content = scanner.next()
    if (content.toIntOrNull() != null) {
        YamlUtil.unpackEnvId = content.toInt()
        if (YamlUtil.unpackEnvId !in 1..3) {
            System.err.println("错误选择")
            exitProcess(0)
        }
    } else {
        System.err.println("错误选择")
        exitProcess(0)
    }

    // 设置脚本
    selectScipt()

}


// 选择打包脚本
private fun selectScipt() {

    val scriptFile = "$rootPath/data/script"
    val scriptPath = PackPath(scriptFile)

    val fileObj = mutableListOf<String>()

    val files = scriptPath.toFile().listFiles()
    for (file in files) {
        val filePath = file.path.replace(scriptFile, "")
        if (file.name.startsWith("script_")) {
            fileObj.add(filePath)
            fileObj.add(file.path)
        }
    }

    println("选择要执行的脚本")
    var index = 1
    for (i in fileObj.indices step 2) {
        println("$index. ${fileObj[i]}")
        index += 1
    }

    val content = scanner.next()
    if (content.toIntOrNull() != null) {
        val contentIndex = content.toInt()
        val path = fileObj.getOrNull(contentIndex* 2)
        // 加载要执行的脚本
        println("执行脚本 $path")
        if (path != null) {
            script.loadFile(listOf(PathUnionType.StringType(path)))
        } else {
            println("脚本不存在 $path")
            exitProcess(0)
        }
    } else {
        println("错误选项")
        exitProcess(0)
    }

}


// pull更新上传
fun pullUpload(file: String) {

//    val repoGitDir = "$file.git"
//    gitPack = luajava.newInstance("com.git.JGitPack")
//
//    println("pull ...")
//
//    result = gitPack.gitPull(repoGitDir);
//
////    println(repoGitDir)
////    println(result)
//
//    pushContent = gitPack.gitLog(repoGitDir);
//
//    Config.isPushOSS = true
//    println(pushContent)
//
//    uploadHandler(repoGitDir, pushContent)
//
//    if result then
//            println("pull 成功");
//    else
//        println("pull 失败");
//    end


}
